<?php
namespace app\admin\controller;
use think\Db;
use think\Session;
class Admin extends Base {

    /*
     * 初始化操作
     */
    public function _initialize(){
        $this->needLogin();
    }
    /**
     * 个人资料
     */
    public function profile()
    {
        $admin_id = $this->getLoginId();
        $db       = Db::name('admin')->where('id', $admin_id)->find();
        $this->assign('userinfo', $db);
        return $this->fetch();
    }

    /**
     * 个人资料|修改
     */
    public function profile_edit()
    {
        $admin_id = $this->getLoginId();

        
        if($this->request->isPost()){
            $nickname = input('post.nickname');
            $email = input('post.email');
            $db = Db::name('admin')->where('id', $admin_id)->update(array('nickname' => $nickname , 'email' => $email));
            if ($db) {
                session('nickname', $nickname);
                $this->success('修改成功','Admin/profile');
            } else {
                $this->error('修改失败','Admin/profile_edit');
            }
        }

        $userInfo = Db::name('admin')->where('id', $admin_id)->find();
        $this->assign('userinfo', $userInfo);
        return $this->fetch();
    }

    /**
     * 修改密码
     */
    public function password()
    {
        $admin_id = $this->getLoginId();

        if($this->request->isPost()){
            $oldPwd = $this->request->param('old_pwd');
            $newPwd = $this->request->param('new_pwd');
            $oldPwdCfm = $this->request->param('new_pwd_cfm');
            
            
            $info = Db::name('admin')->where('id',$admin_id)->find();
            if (!$info || $info['password'] != md5($oldPwd)) {
                $this->error('旧密码不正确','password');
            } else if ($newPwd != $oldPwdCfm) {
                $this->error('两次密码不一致','password');
            } else {
                $db = Db::name('admin')->where('id', $admin_id)->update(array('password' => md5($newPwd)));
                if ($db) {
                    session_unset();
                    session_destroy();
                    session::clear();
                    $this->success('修改成功','Index/login');
                } else {
                    $this->error('修改失败','password');
                }
            }
        }

        return $this->fetch();
    }

}
